import util from "./util"

const HttpErrorCode: any = {
	400: '请求错误',
	401: '未授权，请登陆',
	403: '拒绝访问',
	404: '请求地址出错',
	408: '请求超时',
	500: '服务器内部错误',
	501: '服务未实现',
	502: '网关错误',
	503: '服务不可用',
	504: '网关超时',
	505: 'HTTP版本不受支持'
}

/**
 * 处理请求结果
 * @param result 
 * @returns 
 */
export const checkResult = (result: any) => {
	console.log('checkResult --> ', result)
	let { statusCode, data } = result
	if (statusCode === 200) {
		if (data?.errors && util.isArray(data.errors)) {
			util.totast(data.errors[0].message)
			return { errMsg: data.errors[0].message, from: 'checkResult' }
		}
	} else {
		util.totast(result.message || HttpErrorCode[statusCode])
	}
	return result.data
}

/**
 * 错误处理
 * @param err 
 */
export const catchErr = (err: any) => {
  if (err?.errMsg) {
    util.totast(err.errMsg)
  }
}

/**
 * 检查网络
 * @returns 
 */
export const checkNet = () => {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: res => {
        console.log(res)
        if (res.networkType === 'none') {
          util.totast('网络连接已断开 ~')
        } else {
          resolve(res.networkType)
        }
      },
      fail: error => {
        reject(error)
      }
    })
  })
}

/**
 * 检查 token 是否过期
 */
export function checkToken() {
  const token = uni.getStorageSync('token')
  let tokenObj: any = {}
  let isExpire = false // 是否过期
  let isNeedRefresh = false // 是否需要刷新
  if (!token) {
    isExpire = true
  } else {
    let startDate = uni.getStorageSync('start_date_token')
    tokenObj = JSON.parse(token)
    let endDate = startDate + tokenObj.expires_in * 1000
    let curDate = new Date().getTime()
    let refreshEndDate = startDate + tokenObj.refresh_expires_in * 1000
    if (curDate >= refreshEndDate) {
      isExpire = true
    } else {
      if (endDate - curDate > 30 * 1000) { // 30s
        isExpire = false
      } else {
        isNeedRefresh = true
        isExpire = false
      }
    }
  }

  if (isExpire) {
    uni.removeStorageSync('token')
    uni.removeStorageSync('start_date_token')
  }

  return {
    isExpire,
    isNeedRefresh,
    tokenObj,
  }
}